package com.phattaradanai.ekardex;

import android.app.Activity;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.text.format.Formatter;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.content.Intent;
import android.app.AlertDialog;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.ksoap2.serialization.SoapPrimitive;


public class LoginActivity extends Activity 
{

	public static boolean authen_pass = false;
	public static String txtResult_ws;
	
	
	//Define URL for authen
	/*
	private final String NAMESPACE = "http://tempuri.org/";
	private final String URL = "http://10.6.21.70/ekardexwservice1.asmx?";
	private final String SOAP_ACTION = "http://tempuri.org/UserAuthen";
	private final String METHOD_NAME = "UserAuthen";*/
	
	// Web services for test
	
	private final String NAMESPACE = "http://www.w3schools.com/webservices/";
	private final String URL = "http://www.w3schools.com/webservices/tempconvert.asmx?WSDL";
	private final String SOAP_ACTION = "http://www.w3schools.com/webservices/CelsiusToFahrenheit";
	private final String METHOD_NAME = "CelsiusToFahrenheit";
	
	
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login_page);
		//setContentView(R.layout.activity_get_id);
	}
	
	
	public void onBackPressed(){
		/* Use method onBackPressed for protecting press back button from Login to Main activited of app.*/
		return;
	}
	
	// Link to another Layout with Push Login_Button ( Link to activity_main.xml)
	public void login_button_onClick(View v) {
		
		// Section : Get IP Address from Device
		WifiManager wifiMgr = (WifiManager) getSystemService(WIFI_SERVICE);
		WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
		int ip = wifiInfo.getIpAddress();
		@SuppressWarnings("deprecation")
		String ipAddress = Formatter.formatIpAddress(ip);
		System.out.println(ipAddress);
		
		// Section call web service (SOAP)
		final AlertDialog.Builder ad = new AlertDialog.Builder(this);
		
		final EditText txtUsername = (EditText)findViewById(R.id.username_editText1);
		final EditText txtPassword = (EditText)findViewById(R.id.password_editText2);
		
		// new thread for calling web services
		Thread authen_webserive = new Thread() {
			public void run(){
				SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
				
				// use for add Property to login
				/*
				request.addProperty("username", txtUsername.getText().toString());
				request.addProperty("password", txtPassword.getText().toString());
				System.out.println("id: " + txtUsername.getText().toString());
				System.out.println("password : " + txtPassword.getText().toString());
				//String sCelsius = txtUsername.getText().toString(); */
		
				//use for testing web service
				request.addProperty("Celsius", txtUsername.getText().toString());
				
				SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
				
				envelope.dotNet = true;
				envelope.setOutputSoapObject(request);
				envelope.bodyOut = request;
				System.out.println("Setting Complete");
		
				try{
					HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
					androidHttpTransport.call(SOAP_ACTION, envelope);
					System.out.println("Send data");
					SoapPrimitive resultSOAP = (SoapPrimitive)envelope.getResponse();
					System.out.println("Receive data already");
					
					if(resultSOAP != null){
						SoapObject result = (SoapObject)envelope.bodyIn;
						txtResult_ws = result.getProperty(0).toString();
						System.out.println(result.getProperty(0).toString());
						System.out.println(envelope.bodyIn.toString());
						if(result.getProperty(0).toString() != "|"){
							authen_pass = true;	//authen Pass
						}else{
							authen_pass = false; //username or password is incorrect
						}				
					}
					else{
						authen_pass = false;
						// runOnUiThread for showing message on UI for No Respond form web service
						runOnUiThread(new Runnable(){
							public void run(){
								ad.setTitle("Message Response");
								ad.setMessage("No Response");
								ad.setPositiveButton("OK", null);
								ad.show();
							}
						});
					}
				}
				catch (IOException e) {
					authen_pass = false;
					e.printStackTrace();
				}catch (XmlPullParserException e){
					authen_pass = false;
					e.printStackTrace();
				}
				catch (Exception e) {
					authen_pass = false;
			        e.printStackTrace();
			        
			        // runOnUiThread for showing message on UI
					runOnUiThread(new Runnable(){
						public void run(){
							ad.setTitle("Message Response");
							ad.setMessage("ERROR");
							ad.setPositiveButton("OK", null);
							ad.show();
						}
					});
			    }	
			}
		};
		
		// Command start new thread call web services
		authen_webserive.start();	
		
		new Handler().postDelayed(new Runnable(){
			public void run(){
				/* login pass and change to next page */
				if (authen_pass == true){
					Intent i = new Intent(LoginActivity.this, Main_Activity.class);
					startActivity(i);
				}
			}
		},200);

	}
}		



